﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;

using LeanEngine;
using System.Diagnostics;

namespace LeanEngine.Business
{
    public struct CrashLogger
    {
        #region Method Members

        public static void Log(System.Exception ex, object methodParameter, string applicationName)
        {
            var report = new XmlDocument();
            var xmlNode = report.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);
            var rootElement = report.CreateElement(string.Empty, "CrashReport", string.Empty);

            report.AppendChild(xmlNode);
            report.AppendChild(rootElement);

            var dateElement = report.CreateElement(string.Empty, "Date", string.Empty);
            dateElement.AppendChild(report.CreateTextNode(DateTime.Now.ToString()));

            var errorElement = report.CreateElement(string.Empty, "ProcessingError", string.Empty);
            errorElement.AppendChild(report.CreateTextNode(ex.Message));

            var stackElement = report.CreateElement(string.Empty, "Stack", string.Empty);
            stackElement.AppendChild(report.CreateTextNode(ex.StackTrace));

            var dumpElement = report.CreateElement(string.Empty, "Dump", string.Empty);

            var dumpSerializer = new System.Xml.Serialization.XmlSerializer(methodParameter.GetType());
            using (var textWriter = new System.IO.StringWriter())
            {
                dumpSerializer.Serialize(textWriter, methodParameter);
                dumpElement.AppendChild(report.CreateTextNode(textWriter.GetStringBuilder().ToString()));
            }

            rootElement.AppendChild(dateElement);
            rootElement.AppendChild(errorElement);
            rootElement.AppendChild(stackElement);
            rootElement.AppendChild(dumpElement);

            if (!EventLog.SourceExists(applicationName)) EventLog.CreateEventSource(applicationName, "Application");

            using (var eventLog = new EventLog())
            {
                eventLog.Source = applicationName;
                eventLog.WriteEntry(report.OuterXml, EventLogEntryType.Error);
            }
        }

        #endregion

        #region CA185 FIX

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public static bool operator ==(CrashLogger logger1, CrashLogger logger2)
        {
            return logger1.Equals(logger2);
        }

        public static bool operator !=(CrashLogger logger1, CrashLogger logger2)
        {
            return !logger1.Equals(logger2);
        } 

        #endregion
    }
}
